import Vue from "vue";
import Vuex from "vuex";
// import axios from 'axios'
// import router from '../router'
import appApi from '../../utils/api'
Vue.use(Vuex);
export default {
    namespaced: true,
    state: {
        books: {
            loading_over: true,
            rscontype: false,
            Namedparent: {
                key: '3',
                name: 'qikan'
            },
            detailquery: {
                searchtitle: '',
                id: ''
            },
            searchtype: 0,
            bookinfo_already_show: false,
            show_sider: false,
            show_pagination: false,
            showdetail: false,
            fieldsAllow: {
                sortFields: [
                    { id: "relevance", name: "相关度排序" },
                    { id: "title", name: "书名" },
                    { id: "author", name: "作者" },
                    { id: "publisher", name: "出版社" },
                    { id: "pubYear", name: "出版日期" },
                    { id: "callNo", name: "索书号" },
                ],
                searchAdvCode: { title: "", author: "02", publisher: "03", isbn: "04" },
                searchKeys: [
                    { "id": "", name: "期刊名称" },
                ],
                sortTypes: ["desc", "asc"],
                pageSizeOptions: ['10', '20', '50', '100'],
                defaultPageSize: 12,
            },

            // qs: 请求参数
            qs: {
                pageSize: 12,
                categoryId: '',
                code: '02',
                page: 1,
                key: '',
                resourceType: 1
            },
            // rs:检索结果

            rs: {
                total: 180,
                mulu: [],
                content: [
                    // {
                    //     "author": "(美) 鲁道夫·焦梅蒂著",
                    //     "callNo": "TP316.85/58",
                    //     "docTypeName": "中文图书",
                    //     "isbn": "978-7-111-59829-9",
                    //     "marcRecNo": "39697054624f516a5a3347416b53596b5a4e677741673d3d",
                    //     "num": 1,
                    //     "pubYear": "2018",
                    //     "publisher": "机械工业出版社",
                    //     "title": "GNU/Linux嵌入式快速编程"
                    // },
                    // {
                    //     "author": "杨明华, 谭励, 于重重等编著",
                    //     "callNo": "TP368.5/42",
                    //     "docTypeName": "中文图书",
                    //     "isbn": "978-7-121-06844-7, 978-7-89485-838-2",
                    //     "marcRecNo": "6d372b4458656d77675833676542487a5848492f50513d3d",
                    //     "num": 2,
                    //     "pubYear": "2008",
                    //     "publisher": "电子工业出版社",
                    //     "title": "LAMP网站开发黄金组合Linux+Apache+MySQL+PHP"
                    // },
                ],
                facetsList: [],

                "filters": [
                    { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
                    { "fieldName": "locationFacet", "values": ["03005"] }
                ],
                "limiter": [],
                "sortField": "relevance",
                "sortType": "desc",
                "pageSize": 12,
                "pageCount": 1,
                "locale": "zh_CN",
                "first": true,
            },

        },
    },
    mutations: {
        // 获取详情参数
        ChangeDetailQuery(state, status) {
            state.books.detailquery.searchtitle = status.searchtitle;
            state.books.detailquery.issueId = status.issueId;
        },
        // 侧边栏是否展示
        BOOKINFO_ALREADY_SHOW(state, is_show) {
            state.books.bookinfo_already_show = is_show;
        },
        // 清空搜索
        CLEAR_QS(state) {

            var qs = {
                // searchWords: [{
                //     fieldList: [
                //         { fieldCode: "", fieldValue: "" },
                //         // { "fieldCode": "", "fieldValue": "红楼梦", "fieldConj": "AND" },
                //         // { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                //     ],
                // }],
                // filters: [
                //     // { fieldName: "subjectFacet", values: ["红楼梦", "文学研究"] },
                //     // { fieldName: "locationFacet", values: ["03005"] },
                // ],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 12,
                pageCount: 1, //这个是第几页
                locale: "zh_CN",
                first: true
            };
            state.books.qs = qs;
            state.books.rs.filters = [];
        },
        // 获取过滤条件
        UpdateQsFacets(state, facetsList) {
            state.books.qs.filters = facetsList;
        },
        // 获取过滤条件
        UpdateRsFacets(state, facetsList) {
            state.books.rs.facetsList = facetsList;
        },
        // UpdateRsMulu(state, mulus){
        //     state.books.rs.mulu = mulus;
        // },
        // 获取总数
        UpdateRsTotal(state, total) {
            state.books.rs.total = total;
        },
        // 获取书籍数据
        UpdateRsContent(state, books) {
            state.books.rs.content = books;
        },
        ///
        /**
         * 更新qs 中的检索词
         * 1、更新keyword
         * 2、这里通通重置为第1页
         * 3、
         * searchWords: [
                    {
                        fieldList: [
                            { fieldCode: "", fieldValue: "红楼梦" },
                            { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                        ],
                    }
                ],
         * @param {*} state 
         * @param {检索词，是} search_keyword 
         * 
         */
        // 获取搜索关键字
        UpdateQsSearchKeyWord(state, search_keyword) {
            this.commit(state.books.Namedparent.name + "/UpdateQsSearchKeyWordV2", search_keyword, 1);
        },
        UpdateQsSearchKeyWordV2(state, search_keyword, current_page) {
            state.books.qs.key = search_keyword;
            // state.books.qs.searchWords = [{
            //     fieldList: [
            //         { fieldCode: search_field_code, fieldValue: search_keyword },
            //     ],
            // }];
            state.books.qs.page = current_page;
            state.books.qs.filters = [];
        },
        //高级检索条件，多个关键词
        // UpdateQsSearchFieldListAdv(state, search_field_list) {
        //     state.books.qs.searchWords[0].fieldList = search_field_list;
        // },
        // 年代限制 ["DT:1999/2021"] 这种格式
        UpdateQsLimiter(state, limiter) {
            state.books.qs.limiter = limiter;
        },
        // 获取搜索排序
        ChangeQsSearchField(state, search_field) {
            state.books.qs.searchWords[0].fieldList[0].fieldCode = search_field;
        },
        clearsearchcategoryid(state) {
            state.books.qs.categoryId = ''
        },
        // },
        searchtype(state, type) {
            state.books.searchtype = type;
        },
        // 搜索关键字
        changesearchtitle(state, title) {
            state.books.qs.key = title
        },
        // 搜索类型
        ChangeSortType(state, sortType) {
            state.books.qs.sortType = sortType;
        },
        // 排序
        ChangeSortField(state, sortField) {
            state.books.qs.sortField = sortField;
            // state.books.qs. = sortField;
        },
        // 获取页码
        ChangeCurrentPage(state, currentPage) {
            state.books.qs.page = currentPage;
        },
         // 获取页码
        ChangeCurrentPageWithOutSync(state, currentPage) {
            state.books.qs.page = currentPage;
        },
         // 清空书籍列表
        ClearBooksContents(state) {
            state.books.rs.content = [];
        },

        PARAMS_INIT_QS(state, rs) {
            state.books.rs = rs;

        },
        // 侧边栏是否展示
        SHOW_SIDER(state, status) {
            state.books.show_sider = status;
        },
        // 是否展示分页
        SHOW_PAGINATION(state, status) {
            state.books.show_pagination = status;
        },
        SHOW_DETAIL(state, status) {
            state.books.showdetail = status;
        },
        AddBook(state, {
            author,
            category,
            bisbn,
            isbn,
            pub_year,
            publisher,
            title,
            filetype,
            bookid,
            cover
        }) {
            var book = {
                author: author,
                category: category,
                bisbn: bisbn,
                isbn: isbn,
                pub_year: pub_year,
                publisher: publisher,
                title: title,
                filetype: filetype,
                bookid: bookid,
                cover: cover,
            };
            state.books.rs.content.push(book);
            // console.log("Addbooks ", state.books.rs.content);
        },
        removeFilters(state, index) {
            // 移除弹窗
            state.dialogList.splice(index, 1);
        },
        //  SearchSideUpdateFilters(state, { fieldName, value }, is_search_books) {
        SearchSideUpdateFilters(state, { fieldName }) {
            //数据结构 { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
            // console.log(fieldName, value)
            state.books.qs.categoryId = fieldName;
            this.dispatch("qikan/GetBooks", 1)
                //console.log(is_search_books)
                // state.books.qs.categoryId = '';
                // var filter_len = state.books.qs.filters.length;
                // var findFilter = false;
                // // 如果fieldName对应的fieldName如subjectFacet 是第一次添加
                // for (var i = 0; i < filter_len; i++) {
                //     var filter = state.books.qs.filters[i];
                //     if (filter.fieldName == fieldName) {
                //         findFilter = true;
                //         var index = filter.values.indexOf(value);
                //         // 如果filter 中已经存在value，则之前为选中状态，现在要删除
                //         // 如果之前未选中，则现在要增加
                //         if (index >= 0) {
                //             filter.values.splice(index, 1);
                //             if (state.books.qs.filters[i].values.length == 0) {
                //                 state.books.qs.filters.splice(i, 1);
                //             }
                //             console.log("SearchSideUpdateFilters 1 remove :", filter.values)
                //         } else {
                //             filter.values.push(value);
                //             console.log("SearchSideUpdateFilters 2 add :", filter.values)
                //         }

            //         Vue.set(state.books.qs.filters, i, filter);
            //     }

            // }
            // if (findFilter == false) {
            //     //// 如果fieldName对应的fieldName如subjectFacet 是第一次添加
            //     console.log("SearchSideUpdateFilters 2.5 addFilters: ", fieldName, value);
            //     state.books.qs.filters.push({ "fieldName": fieldName, "values": [value] });
            // }
            // for (i = 0; i < filter_len; i++) {
            //     if (state.books.qs.filters[i].values.length == 0) {
            //         console.log("删除这里的空 filter 1: ", state.books.qs.filters);
            //         state.books.qs.filters.splice(i, 1);
            //         console.log("删除这里的空 filter 2: ", state.books.qs.filters);
            //     }
            // }
            // for (var q = 0; q < state.books.qs.filters.length; q++) {
            //     state.books.qs.categoryId += state.books.qs.filters[q].fieldName + ',';
            // }
            // state.books.qs.categoryId = state.books.qs.categoryId.substring(0, state.books.qs.categoryId.length - 1);
            // is_search_books = true;
            // console.log("SearchSideUpdateFilters  3: ", state.books.qs.filters, fieldName, value);
            // if (is_search_books) {
            //     console.log("SearchSideUpdateFilters  4.1: GetBooks :", is_search_books);
            //     this.dispatch("qikan/GetBooks")
            // } else {
            //     console.log("SearchSideUpdateFilters  4.2:Don't GetBooks :", is_search_books);
            // }
        },
        Changeloading(state, status) {
            state.books.loading_over = status;
        }
    },
    actions: {
        // 获取分类下
        GetBooks(context, status) {
            context.state.books.loading_over = true;
            var params = {};
            if (status == 0) {
                params = {
                    key: context.state.books.qs.key,
                    code: '02',
                    page: context.state.books.qs.page ? context.state.books.qs.page : 1,
                    pageSize: 12
                }
            } else {
                params = {
                    categoryId: context.state.books.qs.categoryId,
                    page: context.state.books.qs.page ? context.state.books.qs.page : 1,
                    pageSize: 12
                }
            }
            // 判断设备
            let flag = navigator.userAgent.match(
                /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            );
            appApi.BokanSearch(params)
                .then(response => {
                    var data = response.data.books;
                    var x = data;
                    if (response.status == 200) {
                        if (context.state.books.rs.content.length > 0) {
                            context.state.books.rs.content = [];
                        }
                        var book_length = response.data.books.length;
                        var books = [];
                        for (var i = 0; i < book_length; i++) {
                            var book = {
                                id: 0,
                                issueId: 0,
                                title: "",
                                author: "",
                                publisher: "",
                                publish_date: "",
                                pub_year: 0,
                                cover: "",
                                intro: "",
                                isbn: "",
                                bisbn: "",
                                category: "",
                                cates: "",
                                booktype: "",
                                filetype: "",
                                bookid: "",
                                assertId: "",
                                src: "",
                                view_count: 0,
                                extid: "",
                                ext: "",
                                created_at: 0,
                                updated_at: 0,
                                pc_read: "",
                                pc_epub: "",
                                wx_read: "",
                                wx_epub: "",
                                detail: "",
                                read: ''
                            };
                            // book.author = x[i].author;
                            // book.category = x[i].callNo;
                            // book.cates = x[i].callNo;
                            book.bisbn = x[i].bisbn;
                            //  book.isbn = x[i].isbn.replace("-", "");
                            book.pub_year = parseInt(x[i].pub_year);
                            book.publish_date = x[i].publish_date ? x[i].publish_date : x[i].issueName;
                            book.publisher = x[i].publisher;

                            book.src = book.publisher;
                            book.title = x[i].title ? x[i].title : x[i].press;
                            book.filetype = x[i].docTypeName;
                            book.bookid = x[i].marcRecNo;
                            book.view_count = x[i].view_count;
                            book.id = parseInt(x[i].id);
                            book.issueId = x[i].issueId;
                            book.intro = x[i].intro;
                            book.cover = x[i].cover ? x[i].cover : x[i].originalCover;
                            book.read = flag ? x[i].wx_read : x[i].pc_read;
                            var isbn = book.isbn;
                            if (isbn.indexOf(",") > 0) {

                                var isbns = isbn.split(",");
                                // console.log("isbn:::", isbn, isbns);
                                if (isbns.length > 1) {
                                    isbn = isbns[0];
                                    // console.log("isbn::1111:", isbn, isbns);
                                    isbn = isbn.replace("-", "");
                                }
                                // console.log("isbn::2222:", isbn, isbns);
                            }

                            books[i] = book;
                            //   that.search_result.books.push(book);
                            // context.commit("AddBook", book);

                            //   console.log(i, " push book:", book);
                            //context.state.books.rs.content.push(book)
                        }
                        context.commit("SHOW_PAGINATION", true);
                        context.commit("SHOW_SIDER", true);
                        // context.state.books.rs.content = books;
                        context.commit("UpdateRsContent", books);
                        context.commit("UpdateRsTotal", parseInt(response.data.totalCount));
                    }
                    // console.log(" state.books:", state.books);
                    context.state.books.loading_over = false;
                    context.state.books.rscontype = true;
                })
                .catch(function(error) {
                    // 请求失败处理
                    console.log("runoob", error);
                });
        },
        // 获取分类
        getsiderbar(context) {
            return appApi.bokancats('')
                .then(response => {
                    if (response.status == 200) {
                        //  context.commit('Updateqssite', response.data.result[0].id);
                        var datas = response.data;
                        var nList = [];
                        // 对slider归类
                        for (var i = 0; i < datas.length; i++) {
                            if (nList.length == 0) {
                                nList.push({
                                    label: datas[i].classname,
                                    facetList: [datas[i]]
                                })
                            } else {
                                var index = nList.findIndex(item => item.label == datas[i].classname);
                                if (index >= 0) {
                                    nList[index].facetList.push(datas[i])
                                } else {
                                    nList.push({
                                        label: datas[i].classname,
                                        facetList: [datas[i]]
                                    })
                                }
                            }
                        }
                        // context.state.books.qs.categoryId = response.data[0].id;
                        context.commit("UpdateRsFacets", nList);
                    }
                })
        },
        // epacall(context) {
        //     axios.get(
        //         'http://login.web.elib.pro/frontend/web/index.php?r=bokan/epac-all-issues&resourceId=452', {
        //             params: context.state.books.qs,
        //             headers: {
        //                 "Content-Type": "text/plain",
        //             },
        //         },
        //         // context.state.books.qs, {
        //         //     headers: {
        //         //         "Content-Type": "text/plain",
        //         //     },
        //         // }
        //     ).then(function(response) {

        //     })
        // }
    },
    getters: {
        // getQS: state => {
        //     return state.books.qs;
        //     // return state.books.filter(todo => todo.done)
        // }
    }
}